<?php

/**
*+------------IMBA浏览记录数据的操作---------------+
*+-------------------------------------------------+
*+--------------用于提供内部接口-------------------+
*+-------------------------------------------------+
*+-@author -+
*+-------------------------------------------------+
*/

namespace Api\Event;

class HistoryEvent extends BaseEvent 
{
	/**
	*添加新的浏览记录
	*@param int $uid 操作的用户标识
	*@param int $videoId 视频标识
	*@return bool
	*/
	public function add($uid, $videoId){
		if (!$uid || !$videoId)
		{
			return;
		}
		$service = D('Common/History', 'Service');
		$map['uid']       = intval($uid);
		$map['video_id'] = intval($videoId);
		$hids = $service->where($map)->getField('id', true);

		$res = D('Common/Video', 'Service')->where(array(
			'id'=>intval($videoId)
		))->getField('type', true);
		$map['type'] = $res[0];
		
		$map['create_time'] = NOW_TIME;

		if(!$hids){
			return $service->add($map);
		}else{
	 		return $service->where(array('id'=>$hids[0]))->save($map);
		}
	}

	/**
	*获取浏览记录
	*@param int $uid 操作的用户标识
	*@return array
	*/
	public function getLists($uid, $limit = 10, $page = 0){
		if (!$uid)
		{
			return;
		}
		$service = D('Common/History', 'Service');
		$vEvent = A('Api/Video', 'Event');
		$map['uid'] = intval($uid);
    	$res = $service->order('create_time DESC')->where($map)->limit($limit);
    	if($page)
    		$res = $res->page($page);
    	//start 获取收录的明细信息 susy.liang
    	/*$data = $res->select();
    	foreach ($data as $k => &$v) {
    		$video = $ ->info($v['video_id']);
    		$v['title'] = $video['title'];
    	}*/
    	$historyData = $res->field('video_id,create_time')->select();
    	//end
    	return $historyData;
	}

    public function lists($filter = [], $limit = 10, $offset = 0)
    {
        $res = service('History')->where($filter);
        $limit && $res->limit($offset, $limit);
        $data = $res->order('create_time DESC')->field('video_id,create_time')->select();
        return $data;
    }

	/**
	*用户浏览总数
	*@param int $uid 用户标识
	*@return int
	*@author susy.liang<susy.liang@ilongyuan.com.cn>
	*/
	public function total($uid, $filter = []){
        $map = ['uid' => intval($uid)];
        $filter && $map = array_merge($map, $filter);
		$total =  D('Common/History', 'Service')->where($map)->count();
		return $total?$total:0;
	}
}